package com.atguigu.exercise;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author : leimingchao
 * @date Date : 2021年10月10日 9:52
 */
public class PictureTest {

    /**
     * 图片的加密
     */
    @Test
    public void test1() {

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("爱情与友情.jpg");
            fileOutputStream = new FileOutputStream("爱情与友情secret.jpg");

            byte[] arr = new byte[20];

            int len;
            while ((len = fileInputStream.read(arr)) != -1) {
                //需要对字节数据进行修改
                //错误的：
                // for (byte b : arr) {
                //     b = (byte) (b ^ 5);
                // }

                //正确的：
                for (int i = 0; i < len; i++) {

                    arr[i] = (byte) (arr[i] ^ 5);
                }

                fileOutputStream.write(arr, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {

                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {

                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 图片的解密
     */
    @Test
    public void test2() {

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("爱情与友情secret.jpg");
            fileOutputStream = new FileOutputStream("爱情与友情5.jpg");

            byte[] arr = new byte[20];

            int len;
            while ((len = fileInputStream.read(arr)) != -1) {
                //需要对字节数据进行修改
                //错误的：
                // for (byte b : arr) {
                //     b = (byte) (b ^ 5);
                // }

                //正确的：
                for (int i = 0; i < len; i++) {

                    arr[i] = (byte) (arr[i] ^ 5);
                }

                fileOutputStream.write(arr, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {

                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {

                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
